﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Commander
{
    /// <summary>
    /// Windows终端模拟器
    /// </summary>
    public class Win32Terminal
    {
        /// <summary>
        /// 模拟终端
        /// </summary>
        public Win32Terminal(string path)
        {
            var handle = Win32Api.GetStdHandle(Win32Api.STD_OUTPUT_HANDLE);
            Win32Api.GetConsoleMode(handle, out int mode);
            Win32Api.SetConsoleMode(handle, mode | Win32Api.ENABLE_VIRTUAL_TERMINAL_PROCESSING);

            string argm = @"powershell.exe";

            Win32Api.STARTUPINFO sInfo = new Win32Api.STARTUPINFO();
            Win32Api.PROCESS_INFORMATION pInfo = new Win32Api.PROCESS_INFORMATION();

            // 创建一个作业
            IntPtr job = Win32Api.CreateJobObject(IntPtr.Zero, null);
            if (!Win32Api.CreateProcess(null, new StringBuilder(argm), new Win32Api.SECURITY_ATTRIBUTES(), new Win32Api.SECURITY_ATTRIBUTES(), false, 0, null, null, ref sInfo, ref pInfo))
            {
                throw new Exception(" 调用失败 ");
            }

            // 将现成添加到作业
            Debug.WriteLine("AssignProcessToJobObject: " + Win32Api.AssignProcessToJobObject(job, pInfo.hProcess));

            uint i = 0;
            Win32Api.WaitForSingleObject(pInfo.hProcess, int.MaxValue);
            Win32Api.GetExitCodeProcess(pInfo.hProcess, ref i);
            Win32Api.CloseHandle(pInfo.hProcess);
            Win32Api.CloseHandle(pInfo.hThread);
        }
    }
}
